﻿using Microsoft.WindowsAPICodePack.Dialogs;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Txt2Markdown
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        /// <summary>
        /// 取消隐藏状态栏
        /// </summary>
        private bool _cancelHideStatusBar = false;
        /// <summary>
        /// 正在隐藏状态栏
        /// </summary>
        private bool _hidingStatusBar = false;

        public MainWindow()
        {
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            InitializeComponent();
        }

        /// <summary>
        /// 设置状态栏文本
        /// </summary>
        /// <param name="text"></param>
        private void SetStatus(string text)
        {
            StatusTextBlock.Text = text;
        }

        private void ShowStatusBar()
        {
            if (_hidingStatusBar)
            {
                _cancelHideStatusBar = true;
            }

            StatusBar1.Visibility = Visibility.Visible;
        }

        /// <summary>
        /// 定时隐藏 StatusBar
        /// </summary>
        /// <param name="seconds"></param>
        private async void HideStatusBar(int seconds)
        {
            _hidingStatusBar = true;
            await Task.Delay(seconds * 1000);
            if (!_cancelHideStatusBar)
            {
                StatusBar1.Visibility = Visibility.Collapsed;
            }
        }

        /// <summary>
        /// 修改章节名为二级标题，并保存章节内容
        /// </summary>
        /// <param name="chapter">章节内容</param>
        /// <param name="filename">不含扩展名的文件名</param>
        /// <param name="targetFolder">目标文件夹</param>
        /// <returns></returns>
        private async Task SaveChapter(string chapter, string filename, string targetFolder)
        {
            // 从章节内容中截取章节名
            var title = chapter.Substring(0, chapter.IndexOf("\r\n"));

            SetStatus($"正在处理 {title}...");

            // 给章节名改为 Markdown 的二级标题
            if (chapter.StartsWith("## "))
            { }
            else if (chapter.StartsWith("##第"))
            {
                chapter = chapter.Replace("##", "## ");
            }
            else
            {
                chapter = "## " + chapter;
            }

            SetStatus($"正在保存 {filename}...");
            await File.WriteAllTextAsync($"{targetFolder}/{filename}.md", chapter, new UTF8Encoding(false));
        }

        /// <summary>
        /// 拆分章节并转换为 .md 文件
        /// </summary>
        /// <param name="sourceFile">源 txt 文件</param>
        /// <param name="targetFolder">目标文件夹</param>
        /// <param name="regex">章节正则表达式</param>
        /// <returns></returns>
        private async Task SplitToMarkdown(string sourceFile, string targetFolder, string regexPattern)
        {
            // 错误消息
            var err = string.Empty;

            if (string.IsNullOrEmpty(sourceFile.Trim()) || !File.Exists(sourceFile))
            {
                err += $"txt文件不存在！";
            }

            if (string.IsNullOrEmpty(targetFolder.Trim()) || !Directory.Exists(targetFolder))
            {
                err += $"{(string.IsNullOrEmpty(err) ? "" : "\r\n")}目标文件夹不存在！";
            }

            if (string.IsNullOrEmpty(regexPattern.Trim()))
            {
                err += $"{(string.IsNullOrEmpty(err) ? "" : "\r\n")}章节表达式不能为空！";
            }

            if (err != string.Empty)
            {
                MessageBox.Show(err, "提醒", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            ShowStatusBar();
            SetStatus($"开始读取 {System.IO.Path.GetFileName(sourceFile)}...");

            // 读取源 txt 文件
            var text = await File.ReadAllTextAsync(sourceFile, Encoding.GetEncoding("GB2312"));

            SetStatus("匹配章节...");
            // 匹配章节
            var mc = Regex.Matches(text, "第[一二两三四五六七八九十○零百千0-9１２３４５６７８９０]{1,12}(章|节|節)");

            SetStatus("截取章节内容...");

            // 章节记数
            int i = 0;

            // 游标
            int pos = 0;
            foreach (Match m in mc)
            {
                if (m.Success)
                {
                    if (m.Index > pos)
                    {
                        // 截取章节内容
                        var chapter = text.Substring(pos, m.Index - pos);

                        // 跳过少于 5 行的内容
                        //if (Regex.Matches(chapter, "\r\n").Count < 5)
                        //{
                        //    continue;
                        //}

                        await SaveChapter(chapter, $"{i.ToString().PadLeft(5, '0')}", targetFolder);

                        ProgressBar1.Value++;

                        // 
                        pos = m.Index + m.Length - m.Groups[0].Length;
                    }

                    i++;
                }
            }

            if (text.Length > pos)
            {
                // 截取章节内容
                var chapter = text.Substring(pos);

                await SaveChapter(chapter, $"{i.ToString().PadLeft(5, '0')}", targetFolder);

                ProgressBar1.Value++;
            }

            SetStatus($"已完成拆分 {System.IO.Path.GetFileName(sourceFile)}.");
            HideStatusBar(3);
        }


        private async Task ModifySummary(string targetFolder)
        {
            if (string.IsNullOrEmpty(targetFolder.Trim()) || !Directory.Exists(targetFolder))
            {
                MessageBox.Show("“目标文件夹”为空或不存在！", "提醒", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            var summaryFile = $"{targetFolder}/SUMMARY.md";

            if (!File.Exists(summaryFile))
            {
                MessageBox.Show("目标文件夹中不存在 SUMMARY.md 文件！\r\n\r\n提示：需要用 gitbook init 命令初始化后才会有 SUMMARY.md 文件。", "文件不存在", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                return;
            }

            var files = Directory.GetFiles(targetFolder);

            SetStatus("读取 SUMMARY.md...");
            var summary = await File.ReadAllTextAsync(summaryFile);

            SetStatus("生成 SUMMARY.md...");
            foreach (var file in files)
            {
                var filename = System.IO.Path.GetFileName(file);
                if (filename.StartsWith("README")
                    || filename.StartsWith("SUMMARY"))
                {
                    continue;
                }

                var lines = await File.ReadAllLinesAsync(file);
                var title = lines[0]; lines = null;

                if (title.Trim().Length > 0)
                {
                    title = title.Replace("## ", "");
                    summary += $"\r\n\r\n* [{title}](./{System.IO.Path.GetFileName(file)})";
                }
            }

            SetStatus("写入 SUMMARY.md...");
            await File.WriteAllTextAsync(summaryFile, summary);

            SetStatus("完成 SUMMARY.md 写入.");
            HideStatusBar(3);
        }

        private void ChooseSourceFileButton_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();
            ofd.Filter = "文本文件(*.txt)|*.txt";
            ofd.CheckPathExists = true;
            ofd.CheckFileExists = true;
            ofd.InitialDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            if (ofd.ShowDialog() == true)
            {
                SourceFileTextBox.Text = ofd.FileName;
            }
        }

        private void ChooseOutFolderButton_Click(object sender, RoutedEventArgs e)
        {
            var dialog = new CommonOpenFileDialog();
            dialog.IsFolderPicker = true;

            if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
            {
                OutFolderTextBox.Text = dialog.FileName;
            }
        }

        private async void AboutButton_Click(object sender, RoutedEventArgs e)
        {

        }

        private async void ConvertButton_Click(object sender, RoutedEventArgs e)
        {
            await SplitToMarkdown(SourceFileTextBox.Text, OutFolderTextBox.Text, RegexTextBox.Text);


            //// 源txt文件
            //var txt = SourceFileTextBox.Text; 
            //// 目标文件夹
            //var dir = OutFolderTextBox.Text;

            //var files = Directory.GetFiles(dir);

            //// 进度条设置
            //StatusBar1.Visibility = Visibility.Visible;
            //ProgressBar1.Value = 1;
            //ProgressBar1.Maximum = files.Length;

            //foreach (var file in files)
            //{
            //    var filename = $"{dir}/{System.IO.Path.GetFileNameWithoutExtension(file)}.md";
            //    File.Move(file, filename);

            //    var lines = await File.ReadAllLinesAsync(filename, Encoding.GetEncoding("GB2312"));
            //    var linelist = lines.ToList().Where(s => s.Trim().Length > 0).ToList();

            //    var title = linelist[0];
            //    if (title.StartsWith("## "))
            //    { }
            //    else if (title.StartsWith("##第"))
            //    {
            //        linelist[0] = title.Replace("##", "## ");
            //    }
            //    else
            //    {
            //        linelist[0] = "## " + title;
            //    }

            //    var chapter = string.Join("\r\n\r\n", linelist);

            //    await File.WriteAllTextAsync(filename, chapter, new UTF8Encoding(false));
            //    ProgressBar1.Value++;
            //}

            //ProgressBar1.Value = 0;
            //StatusBar1.Visibility = Visibility.Collapsed;

            //MessageBox.Show("complated");

        }

        private async void ModifySummaryButton_Click(object sender, RoutedEventArgs e)
        {
            await ModifySummary(OutFolderTextBox.Text);

            //var dir = OutFolderTextBox.Text;

            //if (string.IsNullOrEmpty(dir.Trim()) || !Directory.Exists(dir))
            //{
            //    MessageBox.Show("“目标文件夹”为空或不存在！", "提醒", MessageBoxButton.OK, MessageBoxImage.Warning);
            //    return;
            //}

            //var summaryFile = $"{dir}/SUMMARY.md";

            //if (!File.Exists(summaryFile))
            //{
            //    MessageBox.Show("目标文件夹中不存在 SUMMARY.md 文件！\r\n\r\n提示：需要用 gitbook init 命令初始化后才会有 SUMMARY.md 文件。", "文件不存在", MessageBoxButton.OK, MessageBoxImage.Exclamation);
            //    return;
            //}

            //var files = Directory.GetFiles(dir);

            //var summary = await File.ReadAllTextAsync(summaryFile);

            //foreach (var file in files)
            //{
            //    var filename = System.IO.Path.GetFileName(file);
            //    if (filename.StartsWith("README")
            //        || filename.StartsWith("SUMMARY"))
            //    {
            //        continue;
            //    }

            //    var lines = await File.ReadAllLinesAsync(file);
            //    var title = lines[0]; lines = null;

            //    if (title.Trim().Length > 0)
            //    {
            //        title = title.Replace("## ", "");
            //        summary += $"\r\n\r\n* [{title}](./{System.IO.Path.GetFileName(file)})";
            //    }
            //}

            //await File.WriteAllTextAsync(summaryFile, summary);

            //MessageBox.Show("complated.");
        }

        private void OneClickFinishButton_Click(object sender, RoutedEventArgs e)
        {

        }
    }
}
